package com.rookie.im.codec.utils;

import com.alibaba.fastjson2.JSONObject;
import com.rookie.im.codec.proto.Message;
import com.rookie.im.codec.proto.MessageHead;
import io.netty.buffer.ByteBuf;
import io.netty.util.CharsetUtil;

public class MessageUtils {
    private static final int HEADER_LENGTH = 28;
    public static Message createMessage(MessageHead messageHead, int messageType, byte[] bodyData) {
        Message message = new Message();
        message.setMessageHead(messageHead);
        if (0x0 == messageType) {
            String body = new String(bodyData, CharsetUtil.UTF_8);
            message.setMessagePack(JSONObject.parseObject(body));
        }
        return message;
    }

    public static MessageHead creatMessageHead(ByteBuf in) {
        MessageHead messageHead = new MessageHead();
        int startIndex = in.readerIndex();
        int offset = 0;
        messageHead.setCommand(in.getInt(startIndex+offset));
        offset += 4;
        messageHead.setVersion(in.getInt(startIndex+offset));
        offset += 4;
        messageHead.setClientType(in.getInt(startIndex+offset));
        offset += 4;
        messageHead.setMessageType(in.getInt(startIndex+offset));
        offset += 4;
        messageHead.setAppId(in.getInt(startIndex+offset));
        offset += 4;
        messageHead.setImeiLength(in.getInt(startIndex+offset));
        offset += 4;
        messageHead.setLength(in.getInt(startIndex+offset));

        if (in.readableBytes() < HEADER_LENGTH + messageHead.getImeiLength() + messageHead.getLength()) {
            in.resetReaderIndex();
            return null;
        }
        in.skipBytes(HEADER_LENGTH);
        // imei
        byte[] imeiData = new byte[messageHead.getImeiLength()];
        in.readBytes(imeiData);
        String imei = new String(imeiData, CharsetUtil.UTF_8);
        messageHead.setImei(imei);
        return messageHead;
    }

    public static Message makeMessage(ByteBuf in) {
        if (in.readableBytes() < HEADER_LENGTH) {
            return null;
        }
        MessageHead messageHead = creatMessageHead(in);
        if (messageHead == null) {
            return null;
        }
        // body
        int bodyLength = messageHead.getLength();
        byte[] bodyData = new byte[bodyLength];
        in.readBytes(bodyData);

        return createMessage(messageHead, messageHead.getMessageType(), bodyData);
    }
}
